﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ShowPin.MvcPaging
{
    /// <summary>
    /// 实现分页数据接口
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class PagedList<T> : IPagedList<T>
    {
        /// <summary>
        /// 构造函数 执行分页
        /// </summary>
        /// <param name="source">要执行分页的数据源</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示数据量</param>
        public PagedList(IEnumerable<T> source, int currentPage, int pageSize)
            : this(source.AsQueryable(), currentPage, pageSize)
        {

        }
        /// <summary>
        /// 构造函数 执行分页
        /// </summary>
        /// <param name="source">要执行分页的数据源</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageSize">每页显示数据量</param>
        public PagedList(IQueryable<T> source, int currentPage, int pageSize)
        {
            if (currentPage < 1)
            {
                throw new ArgumentOutOfRangeException("currentPage", "当前页不能小于1");
            }
            if (pageSize < 1)
            {
                throw new ArgumentOutOfRangeException("pageSize", "每页显示数量不能小于1");
            }

            TotalItemCount = source.Count();
            if (TotalItemCount < 0)
            {
                return;
            }
            PageSize = pageSize;
            CurrentPage = currentPage;

            Source = source.Skip(pageSize * (currentPage - 1)).Take(pageSize);
        }

        /// <summary>
        /// 要从中返回元素的 System.Linq.IQueryable<T/>
        /// </summary>
        public IQueryable<T> Source
        {
            get;
            private set;
        }

        /// <summary>
        /// 每页数据量
        /// </summary>
        public int PageSize
        {
            get;
            private set;
        }

        /// <summary>
        /// 当前页
        /// </summary>
        public int CurrentPage
        {
            get;
            private set;
        }

        /// <summary>
        /// 总数据量
        /// </summary>
        public int TotalItemCount
        {
            get;
            private set;
        }
    }
}
